package ru.susu.algebra.centralunits;

import java.io.PrintStream;
import java.util.Iterator;

import ru.susu.algebra.io.FileUtilities;
import ru.susu.algebra.jtex.ITexDocument;
import ru.susu.algebra.methods.IMathMethodPS;
import ru.susu.algebra.properties.IPropertySource;
import ru.susu.algebra.properties.MapPropertySource;

/**
 * @author akargapolov
 * @since: 15.07.2010
 */
public class CentralUnitSearcher<R> implements IMathMethodPS<R>
{
	private static final String FILENAME_PREFIX = "results/alternating/";
	@Override
	public R run(IPropertySource ps) throws Exception
	{
		Iterator<Integer> iterator = (Iterator<Integer>)ps.getValue(CentralUnitsOptions.NUMBERS_ITERATOR);
		IMathMethodPS<ITexDocument> unitsSearcher = (IMathMethodPS<ITexDocument>)Class.forName((String)ps.getValue(CentralUnitsOptions.UNITS_SEARCHER_CLASS)).newInstance();

		while (iterator.hasNext())
		{
			IPropertySource sps = new MapPropertySource();
			Integer number = iterator.next();
			sps.setValue(CentralUnitsOptions.NUMBER, number);
			ITexDocument document = unitsSearcher.run(sps);
			FileUtilities.makeDirectory(FILENAME_PREFIX + number);
			PrintStream stream = FileUtilities.createBufferedFilePrintStream(FILENAME_PREFIX + number + "/centralunits_A" + number + ".tex");
			stream.write(document.generateContent().getBytes("cp1251"));
			//stream.write(document.generateContent().getBytes("utf8"));
			stream.close();
		}
		return null;
	}
}
